package samsung.yx;

import java.io.FileInputStream;
import java.util.Scanner;

public class Airplane01 {

	static int N, boom;
	static int data[][];
	static int mid, coins, max;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(new FileInputStream(
				"C:\\Users\\tstcit\\workspace\\samsung\\Airplane"));
		int T = sc.nextInt();
		for (int t = 0; t < T; t++) {
			// input data
			N = sc.nextInt();
			data = new int[N][5];
			for (int i = N - 1; i >= 0; i--) {
				for (int j = 0; j < 5; j++) {
					data[i][j] = sc.nextInt();
				}
			}
			
			/*for(int k=0;k<N-5;k++){
				for(int i=k;i<k+5;i++){
					for(int j=0;j<5;j++){
						if(data[i][j]==2){
						}
					}
				}
			}*/

			// manage the data
			mid = 2;
			max = -1;
			coins = 0;
			boom = 1;
			dfs(0, mid);
			System.out.println(max);
		}
	}

	private static void dfs(int step, int st) {
		// System.out.println("("+step+","+st+")");
		if (step == N) {// the out door
			if (max < coins) {
				max = coins;
			}
			return;
		}
		// get the left and right
		int left = 0;
		int right = 0;
		if (st == 0) {
			left = 0;
			right = 1;
		} else if (st == 4) {
			left = 3;
			right = 4;
		} else {
			left = st - 1;
			right = st + 1;
		}
		//int temp = 0;
		for (int k = left; k <= right; k++) {
			if (data[step][k] == 1) {
				coins++;
				dfs(step + 1, k);
				coins--;
			}
			if (data[step][k] == 2) {
				coins--;
				dfs(step + 1, k);
				coins++;
			}
			if (data[step][k] == 0) {
				dfs(step + 1, k);
			}
		}
	}

}
